<template>
  <div class="inventory-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-icon class="header-icon"><Box /></el-icon>
          <h1 class="page-title">库存查询</h1>
        </div>
        <div class="header-right">
          <span class="page-subtitle">库存数据统计</span>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 时间查询按钮 -->
      <div class="time-filter-section">
        <div class="time-filter-container">
          <el-button
            v-for="(btn, index) in timeButtons"
            :key="index"
            :type="btn.active ? 'primary' : 'default'"
            @click="handleTimeFilter(btn)"
            class="time-filter-btn"
          >
            {{ btn.label }}
          </el-button>
        </div>
      </div>

      <!-- 图表区域卡片 -->
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><TrendCharts /></el-icon>
            <span>库存统计图表</span>
          </div>
        </template>

        <div class="chart-container">
          <div ref="chartRef" style="width: 100%; height: 400px"></div>
        </div>
      </el-card>

      <!-- 数据表格卡片 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><List /></el-icon>
            <span>库存数据</span>
            <div class="header-actions">
              <el-button
                type="success"
                @click="handleExport()"
                class="export-btn"
              >
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
          </div>
        </template>

        <el-table :data="tableData" style="width: 100%" class="custom-table">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="warehouse_Name" label="仓库名称" width="150" />
          <el-table-column prop="netStock" label="库存数量" width="150" />
          <el-table-column
            prop="inventoryamount"
            label="库存金额"
            width="150"
          />
        </el-table>

        <!-- 合计行 -->
        <div class="total-row">
          <span class="total-label">合计：</span>
          <span class="total-quantity"
            >库存数量 <span class="highlight">{{ totalQuantity }}</span></span
          >
          <span class="total-amount"
            >库存金额
            <span class="highlight">¥{{ totalAmount.toFixed(2) }}</span></span
          >
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 25, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            prev-text="上一页"
            next-text="下一页"
            :total="page.totalCount"
            class="custom-pagination"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { reactive, onMounted, onUnmounted, ref, watch, nextTick } from "vue";

import { ElMessage, ElMessageBox } from "element-plus";
import { BasicsWrite } from "@/http/axiosHelper";
import { useRouter } from "vue-router";
import { statementRed } from "@/http/axiosHelper";
import * as echarts from "echarts";
import {
  Box,
  Calendar,
  TrendCharts,
  List,
  Download,
} from "@element-plus/icons-vue";

const router = useRouter();
const dialogVisible = ref(false);
const chartRef = ref();
let chartInstance: echarts.ECharts | null = null;

// 时间查询按钮配置
const timeButtons = ref([
  { label: "今日", value: "today", active: true },
  { label: "昨日", value: "yesterday", active: false },
  { label: "本周", value: "thisWeek", active: false },
  { label: "上周", value: "lastWeek", active: false },
  { label: "本月", value: "thisMonth", active: false },
  { label: "上月", value: "lastMonth", active: false },
  { label: "最近半年", value: "lastHalfYear", active: false },
  { label: "最近一年", value: "lastYear", active: false },
  { label: "自定义时间", value: "custom", active: false },
]);

// 处理时间筛选
const handleTimeFilter = (btn: any) => {
  timeButtons.value.forEach((b) => (b.active = false));
  btn.active = true;
  getdata(); // 重新获取数据
};

function formatDate(dateStr: string) {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

const page = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0,
});

// 计算合计数据
const totalQuantity = ref(0);
const totalAmount = ref(0);

// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
  try {
    // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
    const response = await statementRed({
      url: "api/Available_Inventory/GetWarehouse_InExport", // 后端接口地址
      method: "GET",
      params: {
        PageIndex: page.PageIndex,
        PageSize: page.PageSize,
      }, // 对应后端 [FromQuery] 的 command 参数
      responseType: "blob", // 关键：指定响应类型为二进制流（Excel 文件）
    });

    // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
    const fileName = getFileNameFromHeaders(response.headers);

    // 3. 生成下载链接并触发下载
    const blob = new Blob([response.data], {
      type:
        response.headers["content-type"] ||
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = fileName; // 文件名从响应头获取或自定义
    document.body.appendChild(a);
    a.click();

    // 4. 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error: any) {
    // 处理错误（如后端返回 401/400 等）
    console.error("导出失败：", error.response?.data || error.message);
    alert("导出失败，请检查参数或重新登录");
  }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
  const contentDisposition =
    headers["content-disposition"] || headers["Content-Disposition"];
  if (!contentDisposition) return "仓库管理.xlsx"; // 默认文件名

  // 解码文件名（处理中文编码问题）
  const match = contentDisposition.match(/filename\*?=([^;]+)/);
  if (match) {
    return decodeURIComponent(match[1].replace(/["']/g, ""));
  }
  return "仓库管理.xlsx";
}

watch(page, () => {
  getdata();
});

onMounted(() => {
  getdata();
  initChart();

  // 监听窗口大小变化，重新调整图表大小
  window.addEventListener("resize", () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  });
});

// 组件卸载时清理资源
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener("resize", () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  });
});

// 初始化图表
const initChart = () => {
  nextTick(() => {
    if (chartRef.value) {
      chartInstance = echarts.init(chartRef.value);
      updateChart();
    }
  });
};

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || !tableData.value.length) return;

  try {
    const warehouseNames = tableData.value.map(
      (item) => item.warehouse_Name || "未知仓库"
    );
    const quantities = tableData.value.map(
      (item) => Number(item.netStock) || 0
    );
    const amounts = tableData.value.map(
      (item) => Number(item.inventoryamount) || 0
    );

    // 计算Y轴的最大值，确保图表能完整显示数据
    const maxQuantity = Math.max(...quantities, 1);
    const maxAmount = Math.max(...amounts, 1);

    // 设置Y轴范围，留出一些空间
    const quantityMax = Math.ceil(maxQuantity * 1.2);
    const amountMax = Math.ceil(maxAmount * 1.2);

    const option = {
      title: {
        text: "库存统计图表",
        left: "center",
        top: 40,
        textStyle: {
          fontSize: 16,
          fontWeight: "bold",
        },
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
        },
        formatter: function (params: any) {
          let result = params[0].name + "<br/>";
          params.forEach((param: any) => {
            if (param.seriesName === "数量") {
              result +=
                param.marker + param.seriesName + ": " + param.value + "<br/>";
            } else {
              result +=
                param.marker +
                param.seriesName +
                ": " +
                param.value.toFixed(2) +
                "<br/>";
            }
          });
          return result;
        },
      },
      legend: {
        data: ["数量", "金额"],
        top: 10,
        left: "center",
        textStyle: {
          fontSize: 14,
          fontWeight: "bold",
        },
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "15%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: warehouseNames,
        axisLabel: {
          rotate: 45,
          interval: 0,
          fontSize: 12,
        },
      },
      yAxis: [
        {
          type: "value",
          name: "数量",
          position: "left",
          max: quantityMax,
          axisLabel: {
            formatter: "{value}",
          },
        },
        {
          type: "value",
          name: "金额",
          position: "right",
          max: amountMax,
          axisLabel: {
            formatter: "{value}",
          },
        },
      ],
      series: [
        {
          name: "数量",
          type: "bar",
          data: quantities,
          itemStyle: {
            color: "#409EFF",
          },
          emphasis: {
            itemStyle: {
              color: "#337ecc",
            },
          },
        },
        {
          name: "金额",
          type: "line",
          yAxisIndex: 1,
          data: amounts,
          itemStyle: {
            color: "#67C23A",
          },
          emphasis: {
            itemStyle: {
              color: "#5daf34",
            },
          },
          smooth: true,
        },
      ],
    };

    chartInstance.setOption(option, true);
  } catch (error) {
    console.error("更新图表失败:", error);
  }
};

// 定义表格数据类型
interface TableDataItem {
  warehouse_Name: string;
  netStock: number;
  inventoryamount: number;
}

const tableData = ref<TableDataItem[]>([]);

const getdata = () => {
  // 从后端获取数据
  statementRed.get("api/Available_Inventory/Available_InventoryHandle", {
    params: {
      PageIndex: page.PageIndex,
      PageSize: page.PageSize,
    },
  })
    .then((res) => {
      if (res.data && res.data.data) {
        console.log(res.data.data);
        tableData.value = res.data.data;
        page.totalCount = res.data.totalCount || 0;

        // 计算合计数据
        totalQuantity.value = tableData.value.reduce(
          (sum, item) => sum + (Number(item.netStock) || 0),
          0
        );
        totalAmount.value = tableData.value.reduce(
          (sum, item) => sum + (Number(item.inventoryamount) || 0),
          0
        );

        // 更新图表
        updateChart();

        if (res.data.data.length === 0) {
          ElMessage.info("暂无数据");
        }
      } else {
        ElMessage.warning("获取数据失败");
        tableData.value = [];
        totalQuantity.value = 0;
        totalAmount.value = 0;
        updateChart();
      }
    })
    .catch((error) => {
      console.error("获取数据失败:", error);
      ElMessage.error("获取数据失败，请稍后重试");
      tableData.value = [];
      totalQuantity.value = 0;
      totalAmount.value = 0;
      updateChart();
    });
};
</script>

<style scoped>
/* 主容器 */
.inventory-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

/* 页面头部 */
.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px 32px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 32px;
  color: #667eea;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  color: #6c757d;
  font-size: 16px;
  font-weight: 500;
  padding: 8px 16px;
  background: rgba(108, 117, 125, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(108, 117, 125, 0.2);
}

/* 主要内容区域 */
.main-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 时间筛选区域 */
.time-filter-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 图表卡片 */
.chart-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.chart-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

/* 表格卡片 */
.table-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.table-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.card-header .el-icon {
  font-size: 20px;
  color: #667eea;
}

.table-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.export-btn {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #28a745, #20c997);
  border: none;
}

.export-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
}

/* 时间筛选按钮样式 */
.time-filter-container {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}

.time-filter-btn {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 80px;
  text-align: center;
}

.time-filter-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.time-filter-btn.el-button--primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
}

.time-filter-btn.el-button--primary:hover {
  background: linear-gradient(135deg, #5a6fd8, #6a4190);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 图表容器样式 */
.chart-container {
  padding: 20px 0;
}

/* 表格样式 */
.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header-wrapper) {
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
}

.custom-table :deep(.el-table__header) {
  color: #2c3e50;
  font-weight: 600;
}

.custom-table :deep(.el-table__body) {
  color: #2c3e50;
}

.custom-table :deep(.el-table__row) {
  color: #2c3e50;
}

/* 合计行样式 */
.total-row {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  margin: 10px 0;
  font-weight: bold;
  color: #606266;
  text-align: center;
  border: 1px solid #e9ecef;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.total-label {
  font-size: 16px;
  color: #2c3e50;
}

.total-quantity,
.total-amount {
  font-size: 14px;
  color: #606266;
}

.highlight {
  color: #f39c12;
  font-weight: 700;
  font-size: 18px;
  text-shadow: 0 1px 2px rgba(243, 156, 18, 0.3);
  background: linear-gradient(135deg, #f39c12, #e67e22);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  padding: 0 4px;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

.custom-pagination {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  padding: 8px 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .inventory-container {
    padding: 16px;
  }

  .page-header {
    padding: 20px 24px;
  }

  .page-title {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .header-actions {
    flex-direction: column;
    gap: 8px;
  }

  .export-btn {
    width: 100%;
  }

  .time-filter-container {
    justify-content: center;
    gap: 8px;
  }

  .time-filter-btn {
    padding: 8px 12px;
    min-width: 60px;
    font-size: 12px;
  }
}

/* 调整只读复选框的样式 */
.readonly-checkbox {
  cursor: default !important;
  .el-checkbox__input {
    cursor: default !important;
    .el-checkbox__inner {
      cursor: default !important;
    }
  }
  .el-checkbox__label {
    cursor: default !important;
  }
}

/* 自定义复选框选中样式，让选中更明显 */
.custom-checkbox {
  /* 未选中状态 */
  .el-checkbox__inner {
    border: 2px solid #dcdfe6; /* 边框加粗 */
    background: #fff;
  }
  /* 选中状态 */
  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #409eff; /* 选中背景色 */
    border-color: #409eff; /* 选中边框色 */
    transform: scale(1.1); /* 选中时稍微放大，突出显示 */
  }
  /* 对勾样式优化 */
  .el-checkbox__input.is-checked .el-checkbox__inner::after {
    width: 6px;
    height: 12px;
  }
  /* 禁用状态下，也保持选中样式清晰 */
  .el-checkbox.is-disabled.is-checked .el-checkbox__inner {
    background-color: #c0c4cc;
    border-color: #c0c4cc;
  }
}
</style>
